package com.example.yuwei.registerlogin_system.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.yuwei.registerlogin_system.R;
import com.example.yuwei.registerlogin_system.bean.User;
import com.example.yuwei.registerlogin_system.presenter.RegisterPresenter;

/**
 * RegisterActivity
 *
 * @author yuwei
 * @date 2019/1/10
 */
public class RegisterActivity extends AppCompatActivity implements RegisterView {

    /**
     * 定义在布局中使用到的控件
     */
    private EditText et_userName;
    private EditText et_realName;
    private EditText et_phoneNumber;
    private EditText et_passWord1;
    private EditText et_passWord2;
    private Spinner sp_cityName;
    private RadioGroup rg_Sex;
    private Button btn_register;
    private String userName;
    private String realName;
    private String sex;
    private String cityName;
    private String phoneNumber;
    private String passWord1;
    private String passWord2;
    private RegisterPresenter registerPresenter;
    private static final int CONNECT_ERROR = 0;
    private static final int SUCCESS = 1;
    private static final int FAILURE = 2;
    private static final int URL_ISEMPTY = 3;
    private static final int CONNECT_TIMEOUT = 4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        registerPresenter = new RegisterPresenter(this);
        init();
    }

    public void init() {
        // 得到布局中使用到的控件
        et_userName = findViewById(R.id.username);
        sp_cityName = findViewById(R.id.cityname);
        et_realName = findViewById(R.id.realname);
        rg_Sex = findViewById(R.id.sex);
        et_phoneNumber = findViewById(R.id.phonenumber);
        et_passWord1 = findViewById(R.id.password1);
        et_passWord2 = findViewById(R.id.password2);
        btn_register = findViewById(R.id.register);

        //性别选项按键
        rg_Sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton select = findViewById(checkedId);
                sex = select.getText().toString();
            }
        });
        //城市选择
        sp_cityName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cityName = getResources().getStringArray(R.array.cityarray)[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //注册按键
        btn_register.setOnClickListener(new View.OnClickListener() {
                                            //注册页面的注册按钮响应
                                            @SuppressLint("HandlerLeak")
                                            @Override
                                            public void onClick(View v) {
                                                if (checkOut()) {
                                                    registerPresenter.register();
                                                }
                                            }
                                        }
        );
    }

    /**
     * 获取控件中的字符串
     */
    public void setUser(User user) {

        user.setUserName(userName);
        user.setPhoneNumber(phoneNumber);
        user.setPassWord(passWord1);
        user.setSex(sex);
        user.setAddress(cityName);
    }

    /**
     * 检测用户输入的信息是否为空
     */
    public boolean checkOut() {
        userName = et_userName.getText().toString().trim();
        realName = et_realName.getText().toString().trim();
        phoneNumber = et_phoneNumber.getText().toString().trim();
        passWord1 = et_passWord1.getText().toString().trim();
        passWord2 = et_passWord2.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            //用户名为空
            showMessage(getResources().getString(R.string.username_is_empty));
            return false;
        }

        if (TextUtils.isEmpty(realName)) {
            showMessage(getResources().getString(R.string.real_name_is_empty));
            return false;
        }

        if (TextUtils.isEmpty(sex)) {
            showMessage(getResources().getString(R.string.select_sex));
            return false;
        }

        if (TextUtils.isEmpty(phoneNumber)) {
            showMessage(getResources().getString(R.string.phone_is_empty));
            return false;
        }

        if (TextUtils.isEmpty(passWord1)) {
            showMessage(getResources().getString(R.string.pass_is_empty));
            return false;
        }

        if (TextUtils.isEmpty(passWord2)) {
            showMessage(getResources().getString(R.string.pass2_is_empty));
            return false;
        }

        if (!passWord1.equals(passWord2)) {
            showMessage(getResources().getString(R.string.twice_pass_diff));
            return false;
        }
        return true;
    }

    /**
     * 发送数据
     */
    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断用户名是否被注册
     *
     * @param username
     * @return
     */
    private boolean isExistUsername(String username) {
        boolean hasUsername = false;
        String[] str = getSharedPreference(username);
        if (str.length > 1) {
            hasUsername = true;
        }
        return hasUsername;
    }

    /**
     * 从sharedPreference提取信息
     */
    public String[] getSharedPreference(String key) {
        String regularEx = "#";
        String[] str = null;
        SharedPreferences sp = getSharedPreferences("loginInfo", MODE_PRIVATE);
        String values;
        values = sp.getString(key, "");
        str = values.split(regularEx);

        return str;
    }

    /**
     * 向sharedPreference写入信息 各项信息可以重复
     *
     * @param key
     * @param values
     */
    public void setSharedPreference(String key, String[] values) {
        String regularEx = "#";
        String str = "";
        SharedPreferences sp = getSharedPreferences("loginInfo", Context.MODE_PRIVATE);
        if (values != null && values.length > 0) {
            for (String value : values) {
                str += value;
                str += regularEx;
            }
            SharedPreferences.Editor et = sp.edit();
            et.putString(key, str);
            et.commit();
        }
    }

    /**
     * 字符数组转json
     *
     * @param strings
     * @return json
     */
    private String stringArraytoJson(String[] strings) {

        if (strings == null) {
            return "";
        }
        if (strings.length > 2) {
            String js = "[{" + "username:" + strings[0] + "password:" + strings[1];
            return js;
        }
        return "";
    }

    @Override
    public User setData(User user) {
        if(user == null){return user;}
        user.setUserName(userName);
        user.setPassWord(passWord1);
        return user;
    }

    @Override
    public Handler showMessage() {
        @SuppressLint("HandlerLeak") Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case CONNECT_ERROR:
                        showMessage(getResources().getString(R.string.connect_error));
                        break;
                    case SUCCESS:
                        showMessage(getResources().getString(R.string.register_success));
                        //注册成功后跳转到登录页面;
                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                        RegisterActivity.this.finish();
                        break;
                    case FAILURE:
                        showMessage(getResources().getString(R.string.user_exist));

                        break;
                    case URL_ISEMPTY:
                        Log.e("input error", "url为空");
                        break;
                    case CONNECT_TIMEOUT:
                        showMessage(getResources().getString(R.string.connect_timeout));
                        break;
                    default:
                }
            }
        };
        return handler;
    }
}
